﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using NetDisk.Models;
using NetDisk.Repository;
using Newtonsoft.Json.Serialization;

namespace NetDisk
{
    public class Startup
    {
        public const string UploadPath = "./uploads";

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool<ApplicationDbContext>(options =>
            {
                options.UseSqlite(Configuration.GetConnectionString("Default"));
            });
            services.AddTransient<IDirIndexRepository, DirIndexRepository>();
            services.AddHttpClient();

            var jwtKey = Encoding.UTF8.GetBytes(Configuration["jwt:key"]);
            var secretKey = new SymmetricSecurityKey(jwtKey);
            var jwtIssuer = Configuration["jwt:issuer"];
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.Configuration = new OpenIdConnectConfiguration();
                    options.Authority = jwtIssuer;
                    options.RequireHttpsMetadata = false;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        IssuerSigningKey = secretKey,
                        ValidAudience = Configuration["jwt:audience"],
                        ValidIssuer = jwtIssuer,
                        ValidateIssuerSigningKey = true,
                        ValidateLifetime = true,
                        ClockSkew = TimeSpan.Zero
                    };
                });

            services.AddControllers()
                .AddNewtonsoftJson(options =>
                {
                    // 配置json解析方式
                    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                    options.SerializerSettings.ContractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = new SnakeCaseNamingStrategy()  // json属性名小写+下划线命名方式
                    };
                });

            services.Configure<ApiBehaviorOptions>(config =>
            {
                config.SuppressModelStateInvalidFilter = false;
                config.InvalidModelStateResponseFactory = actionContext =>
                {
                    var error = actionContext.ModelState.Values.Where(v => v.Errors.Count() > 0)
                        .FirstOrDefault()
                        .Errors.FirstOrDefault()
                        .ErrorMessage;

                    return new BadRequestObjectResult(error);
                };
            });

            #region swagger配置
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "文件管理接口", Version = "v1" });
                c.CustomSchemaIds(cs => cs.FullName);

                // swagger授权
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    In = ParameterLocation.Header,
                    Name = "Authorization",
                    Type = SecuritySchemeType.ApiKey
                });

                //var filePath = Path.Combine(AppContext.BaseDirectory, "Web.Api.xml");
                //c.IncludeXmlComments(filePath);
            });
            #endregion

            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "wwwroot";
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

                #region swagger配置
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "文件管理接口");
                });
                #endregion
            }

            app.UseRouting();

            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                // if (env.IsDevelopment())
                // {
                //     spa.UseReactDevelopmentServer(npmScript: "start");
                // }
            });
        }
    }
}
